<template>
  <div class="basic-search-criteria">
    <a-form ref="formRef" :model="formData" layout="inline" @finish="handleFinish">
      <a-space :size="24" class="flex flex-nowrap">
        <slot></slot>
        <a-form-item class="flex">
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button style="margin-left: 10px" @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup name="BasicSearchCriteria">
import { setRequestApi, setSearchParams, getTableData, resetPaginate } from '../hooks/useTable'
import { ref, toRefs } from 'vue'
import mitt from '@/utils/mitt'

type Props = { api: any; formData: any; formatFormData?: any }
const props = withDefaults(defineProps<Props>(), {
  formatFormData: {}
})
const { api } = props
const { formData, formatFormData } = toRefs(props)

// search
setRequestApi(api)
setSearchParams(formData.value)

// form
const formRef = ref()

const getSearchParams = () => {
  if (Object.keys(formatFormData.value).length) {
    return formatFormData.value
  } else {
    return formData.value
  }
}

const handleFinish = () => {
  const params = getSearchParams()
  setSearchParams(params)
  resetPaginate()
  getTableData()
}

const resetSearch = () => {
  console.log(formData.value, 'formData')
  formRef.value.resetFields()
  mitt.emit('reset-field')
  setTimeout(() => {
    const params = getSearchParams()
    setSearchParams(params)
    resetPaginate()
    getTableData()
  })
}
</script>

<style lang="less" scoped>
.basic-search-criteria {
  .ant-form {
    display: flex;
    flex-wrap: nowrap;
  }
}
</style>
